package cn.iocoder.yudao.module.resource.service.gamematches;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.resource.api.enums.EnumAipError;
import cn.iocoder.yudao.module.resource.controller.admin.gamematches.vo.GameMatchesPageReqVO;
import cn.iocoder.yudao.module.resource.controller.admin.gamematches.vo.GameMatchesSaveReqVO;
import cn.iocoder.yudao.module.resource.dal.dataobject.gamematches.GameMatchesDO;
import cn.iocoder.yudao.module.resource.dal.mysql.gamematches.GameMatchesMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 对局记录 Service 实现类
 *
 * @author lizhongwen
 */
@Service
@Validated
public class GameMatchesServiceImpl implements GameMatchesService {

    @Resource
    private GameMatchesMapper gameMatchesMapper;

    @Override
    public String createGameMatches(GameMatchesSaveReqVO createReqVO) {
        // 插入
        GameMatchesDO gameMatches = BeanUtils.toBean(createReqVO, GameMatchesDO.class);
        gameMatchesMapper.insert(gameMatches);
        // 返回
        return gameMatches.getMatchId();
    }

    @Override
    public void updateGameMatches(GameMatchesSaveReqVO updateReqVO) {
        // 校验存在
        validateGameMatchesExists(updateReqVO.getMatchId());
        // 更新
        GameMatchesDO updateObj = BeanUtils.toBean(updateReqVO, GameMatchesDO.class);

        LambdaQueryWrapper<GameMatchesDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(GameMatchesDO::getMatchId, updateObj.getMatchId());
        wrapper.eq(GameMatchesDO::getUserId, updateObj.getUserId());

        gameMatchesMapper.update(updateObj, wrapper);
    }

    @Override
    public void deleteGameMatches(String id) {
        // 校验存在
        validateGameMatchesExists(id);
        // 删除
        gameMatchesMapper.deleteById(id);
    }

    private void validateGameMatchesExists(String id) {
        if (gameMatchesMapper.selectById(id) == null) {
            throw exception(EnumAipError.GAME_MATCHES_NOT_EXISTS);
        }
    }

    @Override
    public GameMatchesDO getGameMatches(Long userId, String id) {
        return gameMatchesMapper.selectOne(GameMatchesDO::getMatchId, id, GameMatchesDO::getUserId, userId);
    }

    @Override
    public PageResult<GameMatchesDO> getGameMatchesPage(GameMatchesPageReqVO pageReqVO) {
        return gameMatchesMapper.selectPage(pageReqVO);
    }

}